﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AiMei.Redis.Core;
namespace AiMei.Redis.Wrapper
{
    public sealed class RedisConnection
    {
        private string _connectionStr;
        private RedisConnect _redisConnect;
        private RedisDataBase RedisDataBase;
        public RedisConnection(string connectionStr)
        {
            _connectionStr = connectionStr;
        }
        public RedisConnection(string host, int port)
        {

        }
        public RedisConnection(string host, int port,string password)
        {
            _redisConnect = new RedisConnect(host, port);
            RedisDataBase = new RedisDataBase(_redisConnect);
            if (string.IsNullOrEmpty(password))
                return;
            var common = $"auth {password}".CreateRedisCommon();
            _redisConnect.clientChannel.WriteAndFlushAsync(common);
            
            TaskCompletionSource<RedisObject> tcs = new TaskCompletionSource<RedisObject>();
            
            Utils.Enqueue(tcs);
            tcs.Task.Wait(10*1000);
            var result = tcs.Task.Result;
            if (result is SimpleString)
            {
                var simpleString = (SimpleString)result;
                if (simpleString.Content != "OK")
                {
                    throw new Exception(simpleString.Content);
                }
            }
        }

        public IDatabase GetDatabase()
        {
            return RedisDataBase;
        }



    }
}
